<?php

namespace app\api\controller;

use addons\alisms\Alisms;
use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class My extends Api
{
    protected $noNeedRight = ['*'];

    /**
     * 个人中心
     */
    function index()
    {
        return $this->success('success', [
            'id' => $this->user_info['id'],
            'nickname' => $this->user_info['nickname'],
            'avatar' => $this->user_info['avatar'],
            'mobile' => $this->user_info['mobile'],
        ]);
    }

    /**
     * 获取购买的视频列表
     */
    function get_my_video_list()
    {
        $where = array(
            'v.media_type' => 1,
            'o.user_id' => $this->user_id,
            'o.state' => 1
        );
        $v_voice_db = Db::name('v_course');
        $list = $v_voice_db->alias('v')
            ->join('fa_v_teacher t', 't.id=v.v_teacher_id', 'left')
            ->join('fa_v_user_order o', 'o.v_course_id = v.id')
            ->where($where)
            ->field("v.id,v.cover_image,v.title,v.count,v.price,v.is_publish,t.name teacher_name")
            ->order('v.is_publish desc,sort desc')->select();

        $this->success('success', $list);
    }

    /**
     * 获取购买的音频列表
     */
    function get_my_voice_list()
    {
        $where = array(
            'v.media_type' => 2,
            'o.user_id' => $this->user_id,
            'o.state' => 1
        );
        $v_voice_db = Db::name('v_course');
        $list = $v_voice_db->alias('v')
            ->join('fa_v_teacher t', 't.id=v.v_teacher_id', 'left')
            ->join('fa_v_user_order o', 'o.v_course_id = v.id')
            ->where($where)
            ->field("v.id,v.cover_image,v.title,v.count,v.price,v.is_publish,t.name teacher_name")
            ->order('v.is_publish desc,sort desc')->select();
        $this->success('success', $list);
    }

    /**
     * 修改手机号
     */
    function modify_mobile()
    {
        $phone = $this->request->post('phone');
        $sms_code = $this->request->post('sms_code');
        if (empty($phone)) {
            $this->error('手机号不能为空');
        }

        if (!preg_match("/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/", $phone)) {
            $this->error('手机号格式不正确');  //不是手机号格式
        }
        $user_db = db::name('user');
        $v_smscode_db = Db::name("v_smscode");

        $where = array();
        $where['phone'] = $phone;
        $result = $v_smscode_db->where($where)->find();
        if ($sms_code != $result['sms_code']) {
            $this->error('验证码有误');
        }
        /*判断验证码是否过期五分钟内有效*/
        if (time() - 300 > $result['time']) {
            $this->error('验证码已过期，请重新获取');
        }
        /*判断该手机号是否已使用*/
        unset($where);
        $where = array(
            'mobile' => $phone
        );
        $user = $user_db->where($where)->find();
        if ($user['id'] == $this->user_id) $this->error("手机号重复，无需更改");

        if ($user) {
            $user_db->where('mobile', $user['mobile'])->update(['mobile' => 0]);
        }

        $user_save = $user_db->where('id', $this->user_id)->setField('mobile', $phone);
        if ($user_save) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 添加评论
     */
    function add_comment()
    {
        $v_course_id = input('v_course_id');
        $content = input('comment');
        if (!$v_course_id || !$content) {
            $this->error("参数有误");
        }
        $data = array(
            'user_id' => $this->user_id,
            'v_course_id' => $v_course_id,
            'content' => $content,
            'is_check' => 1,
            'createtime' => time()
        );
        $v_user_comment_db = Db::name('v_user_comment');
        $comment_id = $v_user_comment_db->insert($data);
        if ($comment_id) {
            $this->success('添加成功');
        } else {
            $this->error("添加失败");
        }
    }

    /**
     * 删除评论
     */
    function delete_comment()
    {
        $id = input('id');
        if ($id < 1) $this->error("评论id出错");

        $v_user_comment_db = Db::name('v_user_comment');
        $info = $v_user_comment_db->where('id', $id)->find();
        if (!$info) $this->error("评论不存在");

        if ($info['user_id'] != $this->user_id) $this->error("不能删除他人的评论");

        $v_user_comment_db->where('id', $id)->delete();

        return $this->success("删除评论成功");
    }

    /**
     *提交建议
     */
    function save_suggest()
    {
        $content = input("content");
        if (empty($content)) $this->error("意见不能为空");

        $suggest_db = Db::name('v_suggest');
        $exist = $suggest_db->where('user_id', $this->user_id)
            ->where('createtime', 'gt', time() - 600)->find();
        if ($exist) $this->error("请不要频繁提交");

        $suggest_db->insert([
            'user_id' => $this->user_id,
            'content' => $content,
            'createtime' => time(),
        ]);

        $this->success("感谢您的反馈");
    }

    /**
     * 获取短信验证码
     */
    function get_message_code()
    {
        $v_smscode_db = Db::name("v_smscode");
        $phone = input('phone');
        $event = input('event');
        if (!$phone || !$event) {
            $this->error('参数错误');
        }
        if (!preg_match("/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/", $phone)) {
            $this->error('手机号格式不正确');  //不是手机号格式
        }
        $where = array();
        $where['phone'] = $phone;
        $result = $v_smscode_db->where($where)->find();
        if ($result) {
            if ($result['time'] + 60 > time()) {
                $this->error('发送次数频繁请稍后重试');
            }
        }

        $user_db = Db::name('user');
        $user = $user_db->where("mobile", $phone)->find();
        if ($user['id'] == $this->user_id) $this->error("新手机号与旧手机号一致，无需更改");

        $code = '';
        $pattern = '1234567890';
        for ($i = 0; $i < 4; ++$i) {
            $code .= $pattern{mt_rand(0, 9)};
        }
        $res = array(
            'mobile' => $phone,
            'event' => $event,
            'code' => $code
        );

        $alisms = new Alisms();
        $info = $alisms->smsSend(json_decode(json_encode($res)));
        $this->success('发送成功', $info);
        if ($info) {
            $this->success('发送成功');
        } else {
            $this->error('发送失败');
        }
    }

    /**
     * 绑定手机号
     */
    function bind_mobile()
    {
        $phone = $this->request->post('phone');
        $sms_code = $this->request->post('sms_code');
        if (empty($phone) || empty($sms_code)) {
            $this->error('参数错误');
        }
        if (!preg_match("/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/", $phone)) {
            $this->error('手机号格式不正确');  //不是手机号格式
        }
        $where = array();
        $where['phone'] = $phone;
        $v_smscode_db = Db::name("v_smscode");
        $result = $v_smscode_db->where($where)->find();
        if ($sms_code != $result['sms_code']) {
            $this->error('验证码有误');
        }
        /*判断验证码是否过期五分钟内有效*/
        if (time() - 300 > $result['time']) {
            $this->error('验证码已过期，请重新获取');
        }
        $user_db = db::name('user');
        /*判断该手机号是否已使用*/
        unset($where);
        $where = array(
            'mobile' => $phone
        );
        $user = $user_db->where($where)->find();

        if ($user) {
            $this->error('该手机号已注册');
        }
        $user_save = $user_db->where(['id' => $this->user_id])->setField('mobile', $phone);
        if ($user_save) {
            $this->success('绑定成功');
        } else {
            $this->error('绑定失败');
        }
    }

    function pay_order()
    {
//        log_print(input('get.'));
        $course_id = input('course_id');
        if ($course_id < 1) {
            log_print("课程ID不存在");
            $this->error("课程ID不存在");
        }

        $course_db = Db::name('v_course');
        $course = $course_db->where("id", $course_id)->find();
        if (empty($course)) {
            log_print("课程不存在");
            $this->error("课程不存在");
        }

        if ($course['is_publish'] == 0) {
            log_print("课程未发布，无需购买");
            $this->error("课程未发布，无需购买");
        }

        $user_db = Db::name('user');
        $mobile = $user_db->where('id', $this->user_id)->value('mobile');
        if (empty($mobile)) $this->error("填写手机号", null, 101);

        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999).$this->user_id;
        $returnurl = input('returnurl');
        $amount = $this->request->request('amount');
        if (!$amount || $amount < 0.01) {
            log_print("支付金额必须大于0");
            $this->error("支付金额必须大于0");
        }

        if (abs($course['price'] - $amount) > 0.01) {
            log_print('支付金额不对，请检查');
            $this->error('支付金额不对，请检查');
        }
        //if (config("app_debug") == true) $amount = 0.01;

        //判断订单是否已购买
        $user_order_db = Db::name('v_user_order');
        $exist = $user_order_db->where('user_id', $this->user_id)
            ->where('v_course_id', $course_id)
            ->find();
        if ($exist) {
            log_print("课程已支付，不要重复支付");
            $this->error("课程已支付，不要重复支付");
        }

        $title = "购买：" . $course['title'];
        $type = "wechat";
        //回调链接
        $notifyurl = config("site.domain") . '/addons/epay/api/notifyx/type/' . $type;

        $third_db = Db::name('third');
        $openid = $third_db->where('user_id', $this->user_id)->value("openid");

        $params = [
            'type' => $type,
            'orderid' => $out_trade_no,
            'title' => $title,
            'amount' => $amount,
            'method' => "mp",
            'openid' => $openid,
            'user_id' => $this->user_id,
            'course_id' => $course_id,
            'auth_code' => "",
            'notifyurl' => $notifyurl,
            'returnurl' => $returnurl,
        ];

        $user_order_log_db = Db::name('v_user_order_log');
        $user_order_log_db->insert([
            'v_user_order_id' => $out_trade_no,
            'user_id' => $this->user_id,
            'v_course_id' => $course_id,
            'content' => json_encode($params),
            'money' => $amount,
            'createtime' => time(),
        ]);

        log_print($params);
        $pay = \addons\epay\library\Service::submitOrder($params);
        $this->success('success', $pay);
    }
}
